package domain

import (
	"github.com/lab-online/internal/shared/valueobject"
	"github.com/lab-online/pkg/util"

	"github.com/lab-online/pkg/logger"
	"github.com/lab-online/pkg/mq"
)

type resultMessageBody struct {
	ReportID uint                      `json:"id"`
	Data     string                    `json:"data"` // json patch string
	Status   []valueobject.Patch[uint] `json:"status"`
}

func (d *Domain) contentConsumer(delivery *mq.Delivery) {
	logger.Debug("report.domain.contentConsumer", string(delivery.Body))
	message, err := util.UnmarshalJSON[resultMessageBody](delivery.Body)
	if err != nil {
		logger.Error("json.Unmarshal", err.Error(), string(delivery.Body))
		return
	}

	reportEntity, err := d.repository.GetReportByID(message.ReportID)
	if err != nil {
		logger.Warn("report.domain.experimentResultConsumer", err.Error())
		delivery.Ack(false)
	}

	reportEntity.ApplyStatusPatch(message.Status)
	if err := reportEntity.ApplyContentPatch([]byte(message.Data)); err != nil {
		logger.Warn("reportEntity.ApplyContentPatch", err.Error())
	}

	if reportEntity, err = d.repository.SaveReport(reportEntity); err != nil {
		logger.Warn("report.domain.experimentResultConsumer", err.Error())
	}

	if err := d.mq.PublishReport(reportEntity); err != nil {
		logger.Warn("report.domain.experimentResultConsumer", err.Error())
	}

	delivery.Ack(false)
}
